package com.itheima.health.controller;

import com.aliyun.oss.ClientException;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.utils.SMSUtils;
import com.itheima.health.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 短信验证码
 */
@RestController
@RequestMapping("/validatecode")
public class ValidateController {
    @Autowired
    private RedisTemplate redisTemplate;
    //体检预约时发送手机验证码
    @RequestMapping("/send4Order.do")
    public Result send4Order(String telephone){
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        try {
            //调用阿里云短信服务API完成发送短信
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", telephone, code.toString());
            //将生成的验证码缓存到redis
            redisTemplate.opsForValue().set(telephone + RedisConstant.SENDTYPE_ORDER, code.toString(), 5, TimeUnit.MINUTES);

            //将生成的验证码返回到页面
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }
    //手机快速登录时发送手机验证码
    @RequestMapping("/send4Login.do")
    public Result send4Login(String telephone){
        Integer code = ValidateCodeUtils.generateValidateCode(6);//生成6位数字验证码
        try {
            //发送短信
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", telephone, code.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //验证码发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        System.out.println("发送的手机验证码为：" + code);
        //将生成的验证码缓存到redis
        redisTemplate.opsForValue().set(telephone + RedisConstant.SENDTYPE_LOGIN, code.toString(), 5, TimeUnit.MINUTES);

        //验证码发送成功
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
